<template>
  <view class="container">
    <view class="header">
      <text class="title">语音翻译</text>
    </view>
    <view class="record-section">
      <button @click="startRecording" class="record-button" v-if="!isRecording && !audioFilePath">🎤 开始录音</button>
      <button @click="stopRecording" class="record-button" v-if="isRecording">⏹ 停止录音</button>
      <button @click="confirmUpload" class="confirm-button" v-if="audioFilePath">确认翻译</button>
    </view>
    <view v-if="translatedText" class="result-section">
      <text class="result-title">翻译结果：</text>
      <text class="translated-text">{{ translatedText }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      audioFilePath: '',
      translatedText: ''
    };
  },
  methods: {
    startRecording() {
      this.isRecording = true;
      uni.startRecord({
        success: (res) => {
          this.audioFilePath = res.tempFilePath;
        },
        fail: () => {
          uni.showToast({ title: '录音失败，请重试', icon: 'none' });
        }
      });
    },
    stopRecording() {
      this.isRecording = false;
      uni.stopRecord();
    },
    confirmUpload() {
      if (this.audioFilePath) {
        this.uploadAudio(this.audioFilePath);
      }
    },
    uploadAudio(filePath) {
      uni.uploadFile({
        url: 'http://localhost:80/api/translate/voice', // 替换为实际的API地址
        filePath: filePath,
        name: 'file',
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.success) {
            this.translatedText = data.translatedText; // 假设API返回的字段
          } else {
            uni.showToast({ title: '翻译失败，请重试', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '上传失败，请重试', icon: 'none' });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  text-align: center;
  padding: 20px;
  background-color: #e3f2fd; /* 蓝色背景 */
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 36px;
  color: #42a5f5; /* 蓝色标题 */
}

.record-section {
  margin-top: 20px;
}

.record-button,
.confirm-button {
  background-color: #42a5f5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 10px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-top: 10px;
}

.record-button:hover,
.confirm-button:hover {
  background-color: #1e88e5;
}

.result-section {
  margin-top: 20px;
}

.result-title {
  font-size: 24px;
  color: #333;
}

.translated-text {
  font-size: 20px;
  color: #666;
  margin-top: 10px;
}
</style>